(function (p) {
    
    var CreateCourse = function ( container ) {
        
        this.CourseSchedule = new Sai.CourseSchedule(container.find("div.course-schedule"),
                                                     container.find("select[name=clasesxsemana]"),
                                                     Sai.HOST + "modules/" + Sai.MODULE + "/actions/create/scripts/validate-course-schedule.php");
        
    }
    CreateCourse.fn = CreateCourse.prototype;
            
    
    p.CreateCourse = CreateCourse;
    
})(Sai);




(function (p) {
    
    var CourseSchedule = function ( days, clasesPerWeek, validationScript ) {
        
        this.days               = days;
        this.schedules          = []
        this.clasesPerWeek      = clasesPerWeek;
        this.validationScript   = validationScript
        
        this.clasesPerWeek.change($.proxy(this.onClasesPerWeekChange, this));
            
        for(var i=0; i < this.days.children().length - 1; i++) {
            
            day = new Sai.CourseSchedule.Schedule($(this.days.children()[i]));
            day.addEventListener(Sai.CourseSchedule.Schedule.CHANGE, $.proxy(this.onScheduleChange, this));
            this.schedules.push(day);
            console.log(day);
            
        }
        
        this.clasesPerWeek.change();
        
    }
    CourseSchedule.fn = CourseSchedule.prototype;
    
    
    CourseSchedule.fn.onClasesPerWeekChange = function ( event ) {
        //console.log();
        
        var day;
        var amount      = Number($(event.currentTarget).val()) - 1;
        var days        = this.days.children().length - 1;
        var difference  = amount - days
        
        //console.log("difference:"+difference);
        if(difference > 0) {
            
            for(var i=0; i < difference; i++) {

                day = new Sai.CourseSchedule.Schedule();
                day.addEventListener(Sai.CourseSchedule.Schedule.CHANGE, $.proxy(this.onScheduleChange, this));
                
                this.schedules.push(day);
                this.days.append(day.container);
                
            }
            
        }else{
            
            for(var i=0; i < Math.abs(difference); i++) {

                day = $(this.days.children()[days - i]);
                day.remove();
                this.schedules.splice(days - i, 1);
                console.log(this.schedules);

            }
            
        }
        
    }
    
    
    CourseSchedule.fn.onScheduleChange = function ( event ) {
        
        //console.log(event);
        for(var i=0; i < this.schedules.length; i++){
            
            if( this.schedules[i] != event.target ){
                
                if(this.schedules[i].getValue().day == event.target.getValue().day &&
                   this.schedules[i].getValue().hour == event.target.getValue().hour &&
                   this.schedules[i].getValue().minutes == event.target.getValue().minutes){
                    console.log(this.schedules[i]);
                    alert("El día elegido ya existe");
                    event.target.reset();
                    return
                }
            }
            
        }
        
        event.target.validate(this.validationScript);
        /*
        if(event.target.getValue()){
            
            event.target.validate();
            
        }*/
        
    }
            
    
    p.CourseSchedule = CourseSchedule;
    
})(Sai);




(function (p) {
    
    var Schedule = function ( container ) {
        
        if(container) {
            
            this.container = container;
            
        }else{
            this.container = $([
            '<label>',
                '<span class="name">Horario:</span>',
                '<select name="day[]">',
                    '<option disabled selected>Día</option>',
                    '<option value="1">Lunes</option>',
                    '<option value="2">Martes</option>',
                    '<option value="3">Miércoles</option>',
                    '<option value="4">Jueves</option>',
                    '<option value="5">Viernes</option>',
                    '<option value="6">Sábado</option>',
                    '<option value="0">Domingo</option>',
                '</select>',
                '&nbsp;-',
                '<select name="hour[]">',
                    '<option disabled selected>Hora</option>',
                    '<option value="0">00</option>',
                    '<option value="1">01</option>',
                    '<option value="2">02</option>',
                    '<option value="3">03</option>',
                    '<option value="4">04</option>',
                    '<option value="5">05</option>',
                    '<option value="6">06</option>',
                    '<option value="7">07</option>',
                    '<option value="8">08</option>',
                    '<option value="9">09</option>',
                    '<option value="10">10</option>',
                    '<option value="11">11</option>',
                    '<option value="12">12</option>',
                    '<option value="13">13</option>',
                    '<option value="14">14</option>',
                    '<option value="15">15</option>',
                    '<option value="16">16</option>',
                    '<option value="17">17</option>',
                    '<option value="18">18</option>',
                    '<option value="19">19</option>',
                    '<option value="20">20</option>',
                    '<option value="21">21</option>',
                    '<option value="22">22</option>',
                    '<option value="23">23</option>',
                '</select>',
                '&nbsp;:',
                '<select name="minutes[]">',
                    '<option disabled selected>Minuto</option>',
                    '<option value="0">00</option>',
                    '<option value="5">05</option>',
                    '<option value="10">10</option>',
                    '<option value="15">15</option>',
                    '<option value="20">20</option>',
                    '<option value="25">25</option>',
                    '<option value="30">30</option>',
                    '<option value="35">35</option>',
                    '<option value="40">40</option>',
                    '<option value="45">45</option>',
                    '<option value="50">50</option>',
                    '<option value="55">55</option>',
                    '<option value="60">60</option>',
                '</select>',
                '&nbsp;hs&nbsp;',
            '</label>'
            ].join(""));
            
        }
        
        this.day     = this.container.find("select[name='day[]']");
        this.hour    = this.container.find("select[name='hour[]']");
        this.minutes = this.container.find("select[name='minutes[]']");
        this.status;
        
        this.day.change($.proxy(this.onChange, this));
        this.hour.change($.proxy(this.onChange, this));
        this.minutes.change($.proxy(this.onChange, this));
        
    }
    Schedule.fn = Schedule.prototype;
    
    
    EventDispatcher.prototype.apply(Schedule.prototype);
      
    
    Schedule.fn.getValue = function () {
        
        return {
            day: this.day.val(),
            hour: this.hour.val(),
            minutes: this.minutes.val()
        }
        
    }
      
    
    Schedule.fn.getStatus = function () {
        
        return this.status
        
    }
      
    
    Schedule.fn.reset = function () {
        
        $(this.day.children()[0]).attr("selected", "true");
        $(this.hour.children()[0]).attr("selected", "true");
        $(this.minutes.children()[0]).attr("selected", "true");
        this.changeState();
        
    }
      
    
    Schedule.fn.changeState = function ( state ) {
        
        var label;
        
        switch (state) {
            case Schedule.LOADING:
                label = $(Schedule.LOADING_LABEL);
            break
            case Schedule.AVAILABLE:
                label = $(Schedule.AVAILABLE_LABEL);
            break
            case Schedule.NO_AVAILABLE:
                label = $(Schedule.NO_AVAILABLE_LABEL);
            break
            default:
            break
        }
        this.container.find("span.label").remove();
        
        if(label){
            this.container.append(label);
        }
        
        this.status = state;
        
    }
    
    
    Schedule.fn.validate = function ( validationScript ) {
        
        //console.log("validate");
        this.changeState(Schedule.LOADING);
        $.ajax({
            type: "POST",
            url: validationScript,
            data: {
                day: this.day.val(),
                hour: this.hour.val(),
                minute: this.minutes.val()
            },
            success: $.proxy(this.onValidationReceived, this),
            error: $.proxy(this.onValidationError, this)
        });
        
    }
    
    
    Schedule.fn.onChange = function ( event ) {
        
        //console.log("onChange");
        if(this.day.val() !== null && 
           this.hour.val() !== null && 
           this.minutes.val() !== null ) {
            
            //this.validate();
            //console.log("dispatch");
            this.dispatchEvent({ type:Schedule.CHANGE });
            
        }
        
    }
    
    
    Schedule.fn.onValidationReceived = function ( data ) {
        
        console.log("onValidationReceived");
        console.log(data);
        
        if(Number(data)){
            
            this.changeState(Schedule.AVAILABLE);
            
        }else{
            
            this.changeState(Schedule.NO_AVAILABLE);
            
        }
        
    }
    
    
    Schedule.fn.onValidationError = function ( jqXHR, textStatus ) {
        
        console.log(jqXHR);
        alert(textStatus + " " + jqXHR.responseText);
        
    }
    
    
    Schedule.LOADING_LABEL        = '<span class="label"><span class="icon back-in-time"></span> Comprobando disponibilidad</span>';
    Schedule.AVAILABLE_LABEL      = '<span class="label label-success"><span class="icon check"></span> Disponible</span>';
    Schedule.NO_AVAILABLE_LABEL   = '<span class="label label-danger"><span class="icon cross"></span> No disponible</span>';
    
    Schedule.LOADING        = "loading";
    Schedule.AVAILABLE      = "available";
    Schedule.NO_AVAILABLE   = "no-available";
    
    Schedule.CHANGE = "onChange";
    
    
    p.Schedule = Schedule;
    
})(Sai.CourseSchedule);
    



$(document).ready(function () {
    
    new Sai.CreateCourse( $("#group-create") );
    
});